package com.karrim.server.util.file;

import com.google.inject.Singleton;
import com.karrim.server.util.file.abstr.AbstractBlockingHttpServlet;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.SystemUtils;

/**
 *
 * @author andrea.cantafio
 */
@Singleton
public class FileServlet extends AbstractBlockingHttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (ServletFileUpload.isMultipartContent(req)) {
            try {
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                List<FileItem> items = upload.parseRequest(req);
                for (FileItem item : items) {
                    if (item.isFormField()) {
                        continue;
                    }
                    System.out.println(DEFAULT_OUTPUT_DIRECTORY + FilenameUtils.getName(item.getName()));
                    File file = new File(DEFAULT_OUTPUT_DIRECTORY + FilenameUtils.getName(item.getName()));
                    if (file.exists()) {
                        file.delete();
                    }
                    file.createNewFile();
                    try {
                        item.write(file);
                    } catch (Exception ex) {
                        Logger.getLogger(FileServlet.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            } catch (FileUploadException ex) {
                Logger.getLogger(FileServlet.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    private String DEFAULT_OUTPUT_DIRECTORY = SystemUtils.IS_OS_WINDOWS ? "C:\\files\\" : null;
}